/**
 * @author: HZWei
 * @date: 2024/7/14
 * @desc:
 *
 * node.js 执行ts文件, 用tsc编译将ts文件编译成js文件，然后通过node test.js 执行脚本
 * tsc test.ts
 * node test.js
 */
import * as fs from "fs";
import {readdirSync, readFileSync, writeFileSync} from "fs";
import path from "path";
import Handlebars from "handlebars";
import JSON5 from 'json5';
import {PageInfo, PluginConfig, RouteMap, RouteInfo} from './src/model'

function getFilesInDir(dirPath: string) {
    let files = new Array<string>()

    function find(currentDir: string) {
        const contents = readdirSync(currentDir, {withFileTypes: true})
        contents.forEach((value, index) => {
            // 文件目录路径 + 文件名称  = 文件路径
            const filePath = path.join(currentDir, value.name)
            if (value.isDirectory()) {
                find(filePath)
            } else if (value.isFile()) {
                files.push(filePath)
            }
        })
    }

    find(dirPath)
    console.log(files)
    return files
}

// const  files = getFilesInDir('./src')

function generateFile(dir: string, fileName: string) {
    // 读取模板文件
    const source = fs.readFileSync('template2.txt', 'utf8')
    // 编译模版
    const template = Handlebars.compile(source)
    // 提供数据 并渲染模版
    const content = {
        title: "我是标题",
        content: "我是内容"
    }
    const html = template(content)
    console.log(html)
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, {recursive: true});
    }
    writeFileSync(`${dir}${fileName}`, html)
}

// 注意：目录必须带反斜杆的
// generateFile('./src/test/','test2.html')


// const importPath = path.relative(`${config.modulePath}/${config.builderDir}`, sourcePath).replaceAll("\\", "/").replaceAll(".ets", "");




const config = new PluginConfig();
const routeMap = new RouteMap()
config.scanDir = 'src/main/ets/'
config.generatedDir = 'src/main/ets/generated/'
config.indexDir = __dirname
config.moduleJsonPath = 'src/main/ets/module.json5'
config.routerMapPath = 'src/main/ets/resources/base/profile/route_map.json'

function generateBuilderRegisterFile(dir: string, fileName: string) {

    const source = fs.readFileSync('builderRegister2.txt', 'utf8')
    const template = Handlebars.compile(source)
    const content = {
        pageList: getPageInfos()
    }
    const ts = template(content)
    console.log(ts)
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, {recursive: true});
    }
    writeFileSync(`${dir}${fileName}`, ts)
    generateRouterMap(content.pageList)
}

function generateRouterMap(pageInfos: Array<PageInfo>) {
    const routeMap = new RouteMap()
    routeMap.routerMap = pageInfos.map((item) => {
        const route = new RouteInfo()
        route.name = item.pageName
        route.pageSourceFile = item.absolutePath.replace(/\\/g, '/')
        route.buildFunction = item.buildFunctionName
        return route
    })
    writeFileSync(config.routerMapPath, JSON.stringify(routeMap, null, 2), {encoding: "utf8"})


}


function getPageInfos() {
    // 模拟测试
    const pagePaths = getFilesInDir(config.scanDir).filter((item) => item.includes("-page.ts"))
    return pagePaths.map((filePath) => {
        // 文件名：不包括后缀
        const fileName = path.basename(filePath, path.extname(filePath))
        const pageName = convert(fileName)
        // 将绝对路径转换成相对路径
        const importPath = path.relative(config.generatedDir, filePath.substring(0, filePath.lastIndexOf('.'))).replace(/\\/g, '/')
        return {
            pageName: pageName,
            importPath: importPath,
            absolutePath: filePath,
            buildFunctionName: `${pageName}Builder`
        } as PageInfo
    })
}


function convert(str: string): string {
    return str.replace(/(?:^|-)\w/g, (match) => match.toUpperCase().replace(/-/, ''));
}




function generateIndexFile(dir: string) {
    const indexPath = `${config.indexDir}/Index2.ts`
    const builderRegisterPath = path.join(config.generatedDir, 'builderRegister.ts')
    const importPath = path.relative(dir, builderRegisterPath.substring(0, builderRegisterPath.lastIndexOf('.'))).replace(/\\/g, '/')
    const data: string = `export * from './${importPath}'`
    if (!fs.existsSync(indexPath)) {
        fs.writeFileSync(indexPath, data)
        return
    }
    const content = fs.readFileSync(indexPath, {encoding: "utf8"})
    const lines = content.split('\n')
    const target = lines.find((item) => item === data)
    if (!target) {
        lines.push(data)
        fs.writeFileSync(indexPath, lines.join('\n'), {encoding: "utf8"})
    }
}



function checkIfModuleRouterMapConfig() {
    // 检查 module.json5文件是否配置路由表文件
    if (!fs.existsSync(config.moduleJsonPath)) return;
    const content = readFileSync(config.moduleJsonPath, "utf8")
    const module = JSON5.parse(content)
    if (module.module.routerMap) return;
    module.module.routerMap = "$profile:route_map"
    fs.writeFileSync(config.moduleJsonPath, JSON.stringify(module, null, 2), {encoding: "utf8"})

}

generateBuilderRegisterFile(config.generatedDir, 'builderRegister.ts')
generateIndexFile(config.indexDir)
checkIfModuleRouterMapConfig()

